// pages/login/login.js
const { authManager } = require('../../utils/auth');

Page({
  data: {
    statusBarHeight: 0, // 状态栏高度
    username: '',
    password: '',
    loading: false
  },

  onLoad() {
    // 获取系统信息，适配状态栏高度
    const systemInfo = wx.getSystemInfoSync();
    const statusBarHeight = systemInfo.statusBarHeight || 0;
    
    this.setData({
      statusBarHeight: statusBarHeight
    });
    
    wx.hideHomeButton();
    // 检查是否已登录，如果已登录则直接跳转到欢迎页
    if (authManager.checkLoginStatus().isLoggedIn) {
      wx.redirectTo({
        url: '/pages/welcome/welcome'
      });
    }
  },

  // 获取用户名输入
  onUsernameInput(e) {
    this.setData({
      username: e.detail.value
    });
  },

  // 获取密码输入
  onPasswordInput(e) {
    this.setData({
      password: e.detail.value
    });
  },

  // 账号密码登录
  onPasswordLogin() {
    const { username, password } = this.data;

    // 输入验证
    if (!username.trim()) {
      wx.showToast({
        title: '请输入用户名',
        icon: 'none'
      });
      return;
    }

    if (!password.trim()) {
      wx.showToast({
        title: '请输入密码',
        icon: 'none'
      });
      return;
    }

    this.setData({ loading: true });

    wx.request({
      url: `${getApp().globalData.serverUrl}/wx_loginwx/`,
      method: 'POST',
      data: {
        username: username.trim(),
        password: password.trim()
      },
      success: (res) => {
        if (res.data.status === true) {
          this.handleLoginSuccess(res.data, username.trim(), password.trim());
        } else {
          wx.showToast({
            title: res.data.message || '登录失败',
            icon: 'error'
          });
        }
      },
      fail: (err) => {
        console.error('登录请求失败:', err);
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        });
      },
      complete: () => {
        this.setData({ loading: false });
      }
    });
  },
  onShareAppMessage() {
  },
  // 处理登录成功
  handleLoginSuccess(data, username, password) {
    try {
      // 后端返回统一的用户信息对象
      const userInfo = data.user_info;
      
      // 保存登录信息
      authManager.saveLoginInfo(username, password, userInfo);

      wx.showToast({
        title: '登录成功',
        icon: 'success'
      });

      // 检查微信绑定状态
      this.checkWechatBinding(username);
    } catch (e) {
      console.error('处理登录数据失败:', e);
      wx.showToast({
        title: '登录数据处理失败',
        icon: 'error'
      });
    }
  },

  // 检查微信绑定状态
  checkWechatBinding(username) {
    wx.request({
      url: `${getApp().globalData.serverUrl}/wx_CheckWechatBinding/`,
      method: 'POST',
      data: { zh_name: username },
      success: (res) => {
        if (res.data.status && !res.data.is_bound) {
          // 未绑定微信，询问是否绑定
          wx.showModal({
            title: '绑定微信',
            content: '为了更好的使用体验，建议您绑定微信账号，是否现在绑定？',
            confirmText: '立即绑定',
            cancelText: '稍后再说',
            success: (modalRes) => {
              if (modalRes.confirm) {
                this.bindWechatAccount(username);
              } else {
                this.navigateToHome();
              }
            }
          });
        } else {
          this.navigateToHome();
        }
      },
      fail: () => {
        this.navigateToHome();
      }
    });
  },

  // 微信登录
  onWechatLogin() {
    wx.showModal({
      title: '微信登录',
      content: '是否授权微信登录？',
      success: (res) => {
        if (res.confirm) {
          this.performWechatLogin();
        }
      }
    });
  },

  // 执行微信登录
  performWechatLogin() {
    wx.showLoading({ title: '登录中...' });

    wx.getUserInfo({
      success: (res) => {
        const userInfo = res.userInfo;
        this.getOpenId(userInfo).then((userInfoWithOpenId) => {
          this.checkWechatUser(userInfoWithOpenId);
        }).catch((err) => {
          wx.hideLoading();
          console.error('获取OpenID失败:', err);
          wx.showToast({
            title: '微信登录失败',
            icon: 'error'
          });
        });
      },
      fail: () => {
        wx.hideLoading();
        wx.showToast({
          title: '获取微信授权失败',
          icon: 'error'
        });
      }
    });
  },

  // 检查微信用户
  checkWechatUser(userInfo) {
    wx.request({
      url: `${getApp().globalData.serverUrl}/wx_GetUserByOpenId/`,
      method: 'GET',
      data: { openid: userInfo.openid },
      success: (res) => {
        wx.hideLoading();
        if (res.data.length > 0 && userInfo.openid) {
          this.handleWechatLoginSuccess(res.data[0], userInfo);
        } else {
          wx.showToast({
            title: '微信未绑定账号',
            icon: 'error'
          });
        }
      },
      fail: () => {
        wx.hideLoading();
        wx.showToast({
          title: '微信登录失败',
          icon: 'error'
        });
      }
    });
  },

  // 处理微信登录成功
  handleWechatLoginSuccess(userData, wechatInfo) {
    // 保存登录信息
    authManager.saveLoginInfo(userData.zh_name, userData.zh_pwd, userData);

    wx.showToast({
      title: '登录成功',
      icon: 'success'
    });

    setTimeout(() => {
      this.navigateToHome();
    }, 1500);
  },


  // 绑定微信账号
  bindWechatAccount(username) {
    wx.showLoading({ title: '绑定中...' });

    wx.getUserInfo({
      success: (res) => {
        const userInfo = res.userInfo;
        this.getOpenId(userInfo).then((userInfoWithOpenId) => {
          this.performWechatBinding(username, userInfoWithOpenId);
        }).catch((err) => {
          wx.hideLoading();
          console.error('获取OpenID失败:', err);
          wx.showToast({
            title: '绑定失败',
            icon: 'error'
          });
          setTimeout(() => this.navigateToHome(), 2000);
        });
      },
      fail: () => {
        wx.hideLoading();
        wx.showToast({
          title: '获取微信授权失败',
          icon: 'error'
        });
        setTimeout(() => this.navigateToHome(), 2000);
      }
    });
  },

  // 执行微信绑定
  performWechatBinding(username, userInfo) {
    // 先检查OpenID是否已被绑定
    wx.request({
      url: `${getApp().globalData.serverUrl}/wx_CheckOpenIdExists/`,
      method: 'GET',
      data: { openid: userInfo.openid },
      success: (res) => {
        if (res.data.exists) {
          wx.hideLoading();
          wx.showToast({
            title: '该微信已绑定其他账号',
            icon: 'none'
          });
          setTimeout(() => this.navigateToHome(), 2000);
          return;
        }

        // 执行绑定
        wx.request({
          url: `${getApp().globalData.serverUrl}/wx_UpdateUserOpenId/`,
          method: 'POST',
          data: {
            zh_name: username,
            openid: userInfo.openid,
          },
          success: (res) => {
            wx.hideLoading();
            if (res.data.status) {
              wx.showToast({
                title: '绑定成功',
                icon: 'success'
              });
            } else {
              wx.showToast({
                title: '绑定失败',
                icon: 'error'
              });
            }
            setTimeout(() => this.navigateToHome(), 1500);
          },
          fail: () => {
            wx.hideLoading();
            wx.showToast({
              title: '绑定失败',
              icon: 'error'
            });
            setTimeout(() => this.navigateToHome(), 2000);
          }
        });
      },
      fail: () => {
        wx.hideLoading();
        wx.showToast({
          title: '检查绑定状态失败',
          icon: 'error'
        });
        setTimeout(() => this.navigateToHome(), 2000);
      }
    });
  },

  // 获取OpenID
  getOpenId(userInfo) {
    return new Promise((resolve, reject) => {
      wx.request({
        url: `${getApp().globalData.serverUrl}/wx_GetOpenId/`,
        method: 'POST',
        success: (res) => {
          if (res.data.status && res.data.appid && res.data.secret) {
            const { appid, secret, APP_URL } = res.data;
            
            wx.login({
              success: (loginRes) => {
                const code = loginRes.code;
                wx.request({
                  url: `${APP_URL}appid=${appid}&secret=${secret}&js_code=${code}&grant_type=authorization_code`,
                  success: (apiRes) => {
                    if (apiRes.data.openid) {
                      userInfo.openid = apiRes.data.openid;
                      resolve(userInfo);
                    } else {
                      reject(apiRes.data.errmsg || '获取OpenID失败');
                    }
                  },
                  fail: reject
                });
              },
              fail: reject
            });
          } else {
            reject(res.data.message || '获取凭证失败');
          }
        },
        fail: reject
      });
    });
  },

  // 跳转到欢迎页
  navigateToHome() {
    wx.redirectTo({
      url: '/pages/welcome/welcome'
    });
  }
});